//
//  SearchOraganizaionViewModel.swift
//  VenusMaster
//
//  Created by weimengran on 2018/12/21.
//  Copyright © 2018 zhaowang. All rights reserved.
//

import UIKit
import Alamofire
import RxSwift

class SearchOraganizaionViewModel: BaseViewModel {
    var modelObserable : [SchoolModel] =  [SchoolModel]()
    var keyWord = ""
    var page = 1
    var task : DataRequest?
    var location : CLLocation?
    var subject = PublishSubject< [SchoolModel]>()

    
    
    func searchWithKeyWords(keyWork : String,loadMore : Bool) -> Void {
        page = loadMore ? page + 1 : 1
        
        let  longitudeStr = NSString(format: "%f" , (location!.coordinate.longitude))
        let latitudeStr = NSString(format: "%f" , (location!.coordinate.latitude))
        
        
        let dict:Dictionary = [
            "longitude":longitudeStr,
            "latitude":latitudeStr,
            "search":keyWord,
            "pageNo":"1",
            "pageSize":"10",
            "timestamp":"2",
            "sign":"2"
            ] as [String : Any]
        let str = dict.formatApi()
        if (task != nil) {
            task?.cancel()
        }
        
        task =  NetworkTools.shareInstance.loadData(.post, URLString: kqueryInstitutionList+str, parameters: dict, finishedCallback: { [unowned self] (result, error) in
            if !error {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
                let modelArr = SchoolModel.tmSpeelBreakModelArr(dataArray) as! [SchoolModel]
                self.modelObserable =  loadMore ? self.modelObserable + modelArr : modelArr;
                self.subject.onNext(self.modelObserable)
            } else {
                self.subject.onError((result as! DataResponse<Any>).error!)
            }
        })
    }
}
